package se.grp03.fmtuner.scheduler.io;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class UdpAdapter implements IOInterface {

	private static DataInputStream inputStream;
	private static DataOutputStream outputStream;
	private static ServerSocket serverSocket;
	private static Socket socket;
	String ip;
	int port;
	
	public UdpAdapter(int port) {
		this.port = port;
	}
	
	public UdpAdapter(String ip, int port) {
		this.ip = ip;
		this.port = port;
	}
        
	@Override
	public void doOpen() {
		if(ip.equals(null))
			socket = null;
		else {
			try {
				socket = new Socket(ip, port);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		inputStream = null;
		outputStream = null;
		
		try {
			serverSocket = new ServerSocket(port);
			System.out.println("** Opened connection on UDP Port: " + port);
		} catch (IOException e) {
			System.err.println(e);
			doClose();
		}
	}

	@Override
	public String doRead() {
		String incomingMessage = null;
		
		try {
			// Accept incoming message.
			socket = serverSocket.accept();
			inputStream = new DataInputStream(socket.getInputStream());
			System.out.println("-> Incoming IP [" + port + "]: " + socket.getInetAddress());
			incomingMessage = inputStream.readUTF();
			System.out.println("-> Incoming Message: " + incomingMessage);
		} catch (IOException e) {
			System.err.println(e);
			doClose();
		}
		
		return incomingMessage;
	}

	@Override
	public void doWrite(String msg) {
		try {
			System.out.println("<- Outgoing Message [" + port + "]: " + msg);
			// Send response to message.
			socket = serverSocket.accept();
			outputStream = new DataOutputStream(socket.getOutputStream());
			outputStream.writeUTF(msg);
		} catch (IOException e) {
			System.err.println(e);
			doClose();
		}
	}

	@Override
	public void doClose() {
		// Close socket, if open.
		if (socket != null) {
			try { socket.close(); }
			catch (IOException e) { System.err.println(e); }
		}
		// Close input stream, if open.
		if (inputStream != null) {
			try { inputStream.close(); }
			catch (IOException e) { System.err.println(e); }
		}
		// Close output stream, if open.
		if (outputStream != null) {
			try { outputStream.close(); }
			catch (IOException e) { System.err.println(e); }
		}
    	System.out.println("** Closed connection on UDP Port: " + port);
	}
}